﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using loginSQL.Util;
using System.IO;
using loginSQL.Pages;
using loginSQL.Window.CollectionEdit;

namespace loginSQL.Window.PageEdit
{
    public partial class BookEdit : Form
    {
        String collectionFilename;
        BookCollection collection;
        int curBookIndex;
        int curPageIndex;

        public BookEdit(String collectionFilename)
        {
            this.collectionFilename = collectionFilename;
            collection = Constants.collections;//BookCollection.Load(collectionFilename);
            InitializeComponent();
            InitCollectionList();
            InitDataSource();
            InitPreview();
        }

        private void InitPreview()
        {
            if (curPageIndex >= 0 && curPageIndex < collection.BookList[curBookIndex].PageCount)
            {
                PageData page = collection.GetPageData(curBookIndex, curPageIndex);
                Bitmap bmp = new Bitmap(800, 1150);
                picBox.Image = bmp;
                Graphics graphics = Graphics.FromImage(picBox.Image);
                graphics.Clear(Color.White);
                if (File.Exists(page.BackgroundFile))
                {
                    graphics.DrawImage(Image.FromFile(page.BackgroundFile), 0, 0, bmp.Width, bmp.Height);
                }
                foreach (String attr in page.AttributeName)
                {
                    if (page.IsVisible(attr))
                    {
                        PointF p = page.GetData(attr);
                        p = new PointF(p.X, p.Y);
                        p.X = Constants.MilimeterXToPixel(p.X);
                        p.Y = Constants.MilimeterYToPixel(p.Y);
                        graphics.DrawString(attr, Constants.TenPixelFont, Brushes.Black, p);
                    }
                }
                graphics.Flush();
            }
        }

        private void InitCollectionList()
        {
            // combo box
            String[] nameArray = collection.BookName.ToArray();
            listBuku.Items.Clear();
            listBuku.Items.AddRange(nameArray);
            if (collection.BookList.Count > 0)
            {
                curBookIndex = 0;
                curPageIndex = 0;
                listBuku.SelectedIndex = curBookIndex;
            }
        }

        private void InitDataSource()
        {
            // data source
            dataGrid.Rows.Clear();
            if (curPageIndex >= 0 && curPageIndex < collection.GetPageCount(curBookIndex))
            {
                PageData page = collection.GetPageData(curBookIndex, curPageIndex);
                foreach (String name in page.AttributeName)
                {
                    addRow(name, page.GetData(name), page.IsVisible(name));
                }
            }
            CheckNavigateButton();
        }

        private void addRow(string name,PointF pos, bool visible)
        {
            Color backColor = Color.White;
            int count = dataGrid.Rows.Count;
            DataGridViewRow row = new DataGridViewRow();

            DataGridViewCellStyle style = new DataGridViewCellStyle();
            if (count % 2 == 0)
                backColor = Color.GreenYellow;
            style.BackColor = backColor; // the color change           
            row.DefaultCellStyle = style;
            row.Height = 30;
            row.MinimumHeight = 30;
            Object[] columns = new Object[4];
            columns[0] = name;
            columns[1] = pos.X;
            columns[2] = pos.Y;
            columns[3] = visible;
            row.CreateCells(dataGrid, columns.ToArray());
            dataGrid.Rows.Add(row);
        }

        private void listBuku_SelectedIndexChanged(object sender, EventArgs e)
        {
            curBookIndex = listBuku.SelectedIndex;
            curPageIndex = 0;
            CheckNavigateButton();
            InitDataSource();
            InitPreview();
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            curPageIndex++;
            CheckNavigateButton();
            InitDataSource();
            InitPreview();
        }

        private void prevButton_Click(object sender, EventArgs e)
        {
            curPageIndex--;
            CheckNavigateButton();
            InitDataSource();
            InitPreview();
        }

        private void CheckNavigateButton()
        {
            if (curPageIndex - 1 < 0)
            {
                prevButton.Enabled = false;
                curPageIndex = 0;
            }
            else
            {
                prevButton.Enabled = true;
            }


            if (curPageIndex + 1 >= collection.GetPageCount(curBookIndex))
            {
                nextButton.Enabled = false;
                curPageIndex = collection.GetPageCount(curBookIndex) - 1;
            }
            else
            {
                nextButton.Enabled = true;
            }

            navigateLabel.Text = (curPageIndex + 1) + "/" + collection.GetPageCount(curBookIndex);
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            collection.SaveBook(curBookIndex);
            MessageBox.Show("Data berhasil disimpan");
        }

        private void dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= dataGrid.RowCount || e.RowIndex<0 || e.ColumnIndex<0 || e.ColumnIndex >= dataGrid.ColumnCount)
                return;
            DataGridViewRow row = dataGrid.Rows[e.RowIndex];
            String attribute = row.Cells[0].Value.ToString();
            float posx = float.Parse(row.Cells[1].Value.ToString());
            float posy = float.Parse(row.Cells[2].Value.ToString());
            bool vis = (bool)row.Cells[3].Value;
            collection.SetPageData(curBookIndex,curPageIndex,attribute, new PointF(posx, posy), vis);
            InitPreview();
        }

        private void saveAsButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter=("Book Collection (*.bcl)|*.bcl|All Files (*.*)|*.*");
            sfd.FilterIndex = 0;
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String filename = sfd.FileName;
                collection.SetBookFilename(curBookIndex,filename);
                collection.SaveBook(curBookIndex);
                collection.Save(collectionFilename);
            }
        }

        private void newPageButton_Click(object sender, EventArgs e)
        {
            collection.AddNewPage(curBookIndex);
            curPageIndex = collection.GetPageCount(curBookIndex) - 1;
            CheckNavigateButton();
            InitDataSource();
            InitPreview();
        }

        private void deleteBookPage_Click(object sender, EventArgs e)
        {
            collection.DeletePage(curBookIndex, curPageIndex);
            curPageIndex--;
            if (curPageIndex < 0) curPageIndex = 0;
            CheckNavigateButton();
            InitDataSource();
            InitPreview();
        }

        private void dataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = dataGrid.Rows[e.RowIndex];
            String attribute = row.Cells[0].Value.ToString();
            float posx = float.Parse(row.Cells[1].Value.ToString());
            float posy = float.Parse(row.Cells[2].Value.ToString());
            bool vis = (bool)row.Cells[3].Value;
            collection.SetPageData(curBookIndex, curPageIndex, attribute, new PointF(posx, posy), vis);
            InitPreview();
        }

        private void dataGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGrid.IsCurrentCellDirty && dataGrid.CurrentCell.ColumnIndex==3)
            {
                dataGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void dataGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 1 || e.ColumnIndex == 2)
            {
                float res;
                if (float.TryParse((String)e.FormattedValue,out res) == false)
                {
                    e.Cancel = true;
                    dataGrid.Rows[e.RowIndex].ErrorText = "the value must be a number";
                }
            }
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    Image img = Image.FromFile(ofd.FileName);
                    PageData page = collection.GetPageData(curBookIndex, curPageIndex);
                    page.BackgroundFile=ofd.FileName;
                    InitPreview();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Invalid Image File!", "Wrong Filename", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btn_koleksi_Click(object sender, EventArgs e)
        {
            CollectionManagement collwindow = new CollectionManagement();
            collwindow.ShowDialog();
            InitCollectionList();
            InitDataSource();
            InitPreview();
        }
    }
}
